package core

import (
	"gitee.com/cooge/impush/message"
	"errors"
	"container/list"
	log "github.com/sirupsen/logrus"
)

type MessageHandlerFunc func(string, *message.Message,error)
var mfilterlist = list.New()
func AddMessageFilter(fhf MessageHandlerFunc) {
	mfilterlist.PushBack(fhf)
}

func messageHeadle(userId string,msg *message.Message,err error){
	for e := mfilterlist.Front(); e != nil; e = e.Next() {
		fh, ok := e.Value.(MessageHandlerFunc)
		if ok {
			fh(userId,msg,err)
		}
	}
}


func SendMessage(userId string, mgs *message.Message) (int, error) {
	us:=GetUser(userId)
	if us!=nil{
		for _,u:=range us{
			ou,ok:=u.(UserConn)
			if ok{
				n,err:=ou.SendMessage(mgs)
				if err==nil{
					messageHeadle(userId,mgs,nil)
					return n,nil
				}else{
					DeleteUser(userId,ou)
					ou.Close(userId)
				}
			}else{
				log.Info("连接类型转换错误","系统内部错误")
			}
		}
	}
	re:=errors.New(message.NO_USER)
	messageHeadle(userId,mgs,re)
	return 0,re
}
